#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
IR 工具类定义
"""

from dataclasses import dataclass, field
from typing import Any, Dict, List, Iterator
from .base import IRNode
from ..symbol_table import Symbol


@dataclass
class IRTemplate(IRNode):
    """模板节点"""

    context: Dict[str, Any] = field(default_factory=dict)
    node_type: str = "template"

    def get_child_nodes(self) -> Iterator[IRNode]:
        """获取所有子节点"""
        for value in self.context.values():
            if isinstance(value, IRNode):
                yield value
        yield from super().get_child_nodes()


@dataclass
class IRRawText(IRNode):
    """原始文本节点"""

    text: str = field(default="")
    node_type: str = "raw_text"


@dataclass
class IRNoneNode(IRNode):
    """空节点"""

    node_type: str = "none"


@dataclass
class IRGroupNode(IRNode):
    """组节点"""

    nodes: List[IRNode] = field(default_factory=list)
    tag: str = field(default="")
    params: Dict[str, Any] = field(default_factory=dict)
    node_type: str = "group"

    def get_child_nodes(self) -> Iterator[IRNode]:
        """获取所有子节点"""
        for child in self.nodes:
            yield child
        yield from super().get_child_nodes()

    @property
    def children(self) -> List[IRNode]:
        """向后兼容性属性"""
        return self.nodes

    @children.setter
    def children(self, value: List[IRNode]) -> None:
        """向后兼容性属性设置器"""
        self.nodes = value

    def merge(self, other: "IRGroupNode") -> None:
        """合并另一个节点组"""
        self.nodes.extend(other.nodes)

    def get_local_symbols(self) -> Iterator["Symbol"]:
        """获取组节点中定义的所有本地符号

        组节点本身不定义符号，但需要递归收集子节点的符号

        Returns:
            本地符号的迭代器
        """
        for node in self.nodes:
            yield from node.get_local_symbols()

    def __eq__(self, other) -> bool:
        """相等判断"""
        if not isinstance(other, IRGroupNode):
            return False
        return self.tag == other.tag and self.params == other.params
